/*
 * Copyright 2014-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.grayson.mykafka.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * KafkaConsumer
 *
 * @Description:
 * @Author: grayson
 * @Version 1.0
 * @Date: 2021-10-11 11:32
 **/
@Component
@Slf4j
public class KafkaConsumer {

    @KafkaListener(topics = {"test_topic"},
            containerFactory = "filterContainerFactory",
            errorHandler = "consumerAwareErrorHandler")
    public String onMessage(ConsumerRecord<?,?> record) throws Exception {
        System.out.println("normal:"+record.topic()+"-"+record.partition()+"-"+record.value());
        return record.value() + "-forward message";
        //throw new Exception("simple consumer exception");
    }


    @KafkaListener(topics = {"topic2"})
    public void onMessage2(ConsumerRecord<?,?> record) throws Exception {
        System.out.println("normal:"+record.topic()+"-"+record.partition()+"-"+record.value());
        //throw new Exception("simple consumer exception");
    }



//    @KafkaListener(id = "consumer1",groupId = "grayson-group",topicPartitions = {
//            @TopicPartition(topic = "test_topic", partitions = { "0" }),
//            @TopicPartition(topic = "topic2", partitions = "0", partitionOffsets = @PartitionOffset(partition = "1", initialOffset = "8"))
//    })
//    public void onMessage2(ConsumerRecord<?,?> record){
//        System.out.println("normal:"+record.topic()+"-"+record.partition()+"-"+record.value());
//    }

    //批量处理消息
    //@KafkaListener(id = "consumer2",groupId = "grayson-group", topics = "test_topic")
    public void onMessage3(List<ConsumerRecord<?, ?>> records){
        System.out.println("message count:" + records.size());
        records.stream().forEach(record -> {
            System.out.println("normal:"+record.topic()+"-"+record.partition()+"-"+record.value());
        });
    }


}
